const socketio = require('socket.io');

let io;
let guestNumber = 1;
const nickNames = {};
const namesUsed = [];
const currentRoom = {};

exports.listen = function (server) {
  io = socketio.listen(server);
  io.set('log level', 1);
  io.sockets.on('connection', function (socket) {
    guestNumber = assignGuestName(socket, guestNumber);
    joinRoom(socket, 'Lobby');
    handleMessageBroadcasting(socket);
    handleNameChangeAttempts(socket);
    handleRoomJoining(socket);
    socket.on('rooms', function () {
      socket.emit('rooms', io.sockets.manager.rooms);
    });
    handleClientDisconnection(socket);
  });
};

// 分配用户昵称
function assignGuestName(socket, guestNumber) {
  const name = `Guest${guestNumber}`;
  nickNames[socket.id] = name;
  socket.emit('nameResult', { success: true, name });
  namesUsed.push(name);
  return guestNumber + 1;
}

// 与进入聊天室相关的逻辑
function joinRoom(socket, room) {
  socket.join(room);
  currentRoom[socket.id] = room;
  socket.broadcast.to(room).emit('message', {
    text: `${nickNames[socket.id]} has joined ${room}.`
  });
  const usersInRoom = io.sockets.clients(room);
  if (usersInRoom.length > 1) {
    const usersInRoomSummary = `Users currently in ${room}: `;
    for (const index in usersInRoom) {
      const usersSocketId = usersInRoom[index].id;
      if (usersSocketId != socket.id) {
        if (index > 0) {
          usersInRoomSummary += ', ';
        }
        usersInRoomSummary += nickNames[usersSocketId];
      }
    }
    usersInRoomSummary += '.';
    socket.emit('message', { text: usersInRoomSummary });
  }
}

// 发送聊天消息
function handleMessageBroadcasting(socket) {}

// 更名请求的处理逻辑
function handleNameChangeAttempts(socket) {
  socket.on('nameAttempt', function (name) {
    if (name.indexOf('Guest') == 0) {
      socket.emit('nameResult', {
        success: false,
        message: 'Names cannot Begin with "Guest"'
      });
    } else if (namesUsed.indexOf(name) == -1) {
      const previousName = nickNames[socket.id];
      const previousNameIndex = namesUsed.indexOf(previousName);
      namesUsed.push(name);
      nickNames[socket.id] = name;
      delete namesUsed[previousNameIndex];
      socket.emit('nameResult', { success: true, name });
    } else {
      socket.emit('nameResult', {
        success: false,
        message: 'That name is already in use.'
      });
    }
  });
}

// 创建房间
function handleRoomJoining(socket) {
  socket.on('join', function (room) {
    socket.leave(currentRoom[socket.id]);
    joinRoom(socket, room.newRoom);
  });
}

// 用户断开连接
function handleClientDisconnection(socket) {
  socket.on('disconnect', function () {
    const nameIndex = namesUsed.indexOf(nickNames[socket.id]);
    delete namesUsed[nameIndex];
    delete nickNames[socket.id];
  });
}
